package com.zgs.mall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.parser.Feature;
import com.zgs.mall.product.service.CategoryBrandRelationService;
import com.zgs.mall.product.vo.Catalog2Vo;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zgs.common.utils.PageUtils;
import com.zgs.common.utils.Query;

import com.zgs.mall.product.dao.CategoryDao;
import com.zgs.mall.product.entity.CategoryEntity;
import com.zgs.mall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //
        List<CategoryEntity> list = baseMapper.selectList(null);
        //组装成父子的树形结构
        //找到所有的一级分类
        List<CategoryEntity> level1Menus = list.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0
        ).map((menus)->{
            menus.setChildren(getChildren(menus,list));
            return menus;
        }).sorted((menu1,menu2)->{
            return (menu1.getSort()==null?0:menu1.getSort())-(menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());
        return level1Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 1.检查当前删除的菜单，是否被别的地方引用
        //逻辑删除
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> list = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, list);
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }

    /**
     * 级联更新所有关联的数据
     * @param category
     */
    @CacheEvict(value = "cata",allEntries = true)
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        //更新自己
        this.updateById(category);
        if(!StringUtils.isEmpty(category.getName())){
            categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
        }



    }
    @Cacheable(value ="cata",key = "#root.method.name",sync = true)
    @Override
    public List<CategoryEntity> getLevel1Category() {
        return this.list(new QueryWrapper<CategoryEntity>().eq("parent_cid",0));
    }


    @Cacheable(value ="cata",key = "#root.method.name",sync = true)
    @Override
    public Map<String, List<Catalog2Vo>> getCatelogJson() {
        /**
         * 1.空结果也将他们缓存上:解决缓存穿透(大量请求命中不存在的缓存,导致请求全部打在DB上)
         * 2.设置过期时间(加随机值) 解决缓存雪崩(大量缓存数据,同时过期)
         * 3.加锁,解决缓存击穿(热点数据,突然过期,大量请求打在DB上)
         */
        //查询所有分类
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        //获得下级
        List<CategoryEntity> level1Category = getCategoryEntities(selectList,0L);
        Map<String, List<Catalog2Vo>> collect = level1Category.stream().collect(Collectors.toMap(
                k -> k.getCatId().toString(),
                v -> {
                    List<CategoryEntity> cata2List = getCategoryEntities(selectList,v.getCatId());
                    List<Catalog2Vo> catelog2VoList = null;
                    if (cata2List != null) {
                        catelog2VoList = cata2List.stream().map(item -> {
                            Catalog2Vo catelog2Vo = new Catalog2Vo(v.getCatId().toString(), item.getCatId().toString(), item.getName(), null);
                            //查询出三级分类
                            List<CategoryEntity> cata3List = getCategoryEntities(selectList,item.getCatId());
                            if (cata3List != null) {
                                List<Catalog2Vo.Catalog3Vo> l3List = cata3List.stream().map(l3 -> {
                                    return new Catalog2Vo.Catalog3Vo(item.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                                }).collect(Collectors.toList());
                                catelog2Vo.setCatalog3List(l3List);
                            }
                            return catelog2Vo;
                        }).collect(Collectors.toList());
                    }
                    return catelog2VoList;
                }));
        return collect;

    }
    public Map<String, List<Catalog2Vo>> getCatelogJson2() {
        /**
         * 1.空结果也将他们缓存上:解决缓存穿透(大量请求命中不存在的缓存,导致请求全部打在DB上)
         * 2.设置过期时间(加随机值) 解决缓存雪崩(大量缓存数据,同时过期)
         * 3.加锁,解决缓存击穿(热点数据,突然过期,大量请求打在DB上)
         */
        String catelogJson = stringRedisTemplate.opsForValue().get("catelogJson");
        if (catelogJson==null){
            Map<String, List<Catalog2Vo>> catelogJsonFromDb = getCatelogJsonFromDbWithRedissonLock();
            return catelogJsonFromDb;
        }
        return JSON.parseObject(catelogJson,new TypeReference<Map<String, List<Catalog2Vo>>>(){});
    }
    @Autowired
    RedissonClient redissonClient;
    private Map<String, List<Catalog2Vo>> getCatelogJsonFromDbWithRedissonLock(){
        RLock cataLock = redissonClient.getLock("cataLock");
        cataLock.lock();
        Map<String, List<Catalog2Vo>> catelogJsonFromDb=null;
        try{
            catelogJsonFromDb = getCatelogJsonFromDb();
        }finally {
            cataLock.unlock();
        }
       return catelogJsonFromDb;

    }
    private Map<String, List<Catalog2Vo>> getCatelogJsonFromDbWithRedisLock(){
        //分布式占锁
        String uuid = UUID.randomUUID().toString();
        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);
        if(lock){
            System.out.println("锁获取成功.....");
            Map<String, List<Catalog2Vo>> catelogJsonFromDb=null;
           try{
              catelogJsonFromDb = getCatelogJsonFromDb();
           }finally {
               //获取值对比+对比成功删除=原子操作 lua脚本
               /**
                * 假设我设置过期时间是1秒
                * A拿到了锁,业务逻辑执行完了,然后要执行删锁,那就要先给redis发送请求,获取值,然后对比是不是A的锁
                * 在这个对比过程中A的的锁到期了被redis删了,代码还没走到删Key那步,啪一声B过来了拿到了锁,
                * 然后A 就把B的锁给删了
                */
//            String lockValue = stringRedisTemplate.opsForValue().get("lock");
//            if(uuid.equals(lockValue)){
//                stringRedisTemplate.delete("lock");
//            }
               String script="if redis.call('get',KEYS[1])==ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
               stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock"), uuid);
           }
            return catelogJsonFromDb;

        }else{
            //休眠10ms重试
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {

            }
            return getCatelogJsonFromDbWithRedisLock();//自旋的方式
        }
    }
    private Map<String, List<Catalog2Vo>> getCatelogJsonFromDb(){
        String catelogJson = stringRedisTemplate.opsForValue().get("catelogJson");
        if (!StringUtils.isEmpty(catelogJson)){
            return JSON.parseObject(catelogJson,new TypeReference<Map<String, List<Catalog2Vo>>>(){});
        }
            //查询所有分类
            List<CategoryEntity> selectList = baseMapper.selectList(null);
            List<CategoryEntity> level1Category = getCategoryEntities(selectList,0L);
            Map<String, List<Catalog2Vo>> collect = level1Category.stream().collect(Collectors.toMap(
                    k -> k.getCatId().toString(),
                    v -> {
                        List<CategoryEntity> cata2List = getCategoryEntities(selectList,v.getCatId());
                        List<Catalog2Vo> catelog2VoList = null;
                        if (cata2List != null) {
                            catelog2VoList = cata2List.stream().map(item -> {
                                Catalog2Vo catelog2Vo = new Catalog2Vo(v.getCatId().toString(), item.getCatId().toString(), item.getName(), null);
                                //查询出三级分类
                                List<CategoryEntity> cata3List = getCategoryEntities(selectList,item.getCatId());
                                if (cata3List != null) {
                                    List<Catalog2Vo.Catalog3Vo> l3List = cata3List.stream().map(l3 -> {
                                        return new Catalog2Vo.Catalog3Vo(item.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                                    }).collect(Collectors.toList());
                                    catelog2Vo.setCatalog3List(l3List);
                                }
                                return catelog2Vo;
                            }).collect(Collectors.toList());
                        }
                        return catelog2VoList;
                    }));
            stringRedisTemplate.opsForValue().set("catelogJson", JSON.toJSONString(collect),1, TimeUnit.DAYS);
             return collect;
    }

    private List<CategoryEntity> getCategoryEntities(List<CategoryEntity> selectList,long parentCid) {
        return selectList.stream().filter(item->item.getParentCid()==parentCid).collect(Collectors.toList());
    }

    private List<Long> findParentPath(Long catelogId,List<Long> list){
        list.add(catelogId);
        CategoryEntity entity = this.getById(catelogId);
        if(entity.getParentCid() !=0){
            findParentPath(entity.getParentCid() ,list);
        }
        return list;
    }
    /**
     * 将分类递归,组成tree树结构
     * @param root
     * @param all
     * @return
     */
    private List<CategoryEntity> getChildren(CategoryEntity root,List<CategoryEntity> all){
        List<CategoryEntity> collect = all.stream().filter(categoryEntity -> {
                    return categoryEntity.getParentCid() == root.getCatId();
                }
        ).map(categoryEntity -> {
            categoryEntity.setChildren(getChildren(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1,menu2)->{
            return (menu1.getSort()==null?0:menu1.getSort())-(menu2.getSort()==null?0:menu2.getSort());
          }
        ).collect(Collectors.toList());
        return collect;
    }
}